import MyButton from "../../Components/MyButton";
import { request } from "../../Api/api";
import {
  Form,
  Input,
  message,
  Tree,
  Checkbox,
  Descriptions,
  Button,
} from "antd";
import React, { useState, useEffect, useRef, useCallback } from "react";
import { useLocation } from "react-router-dom";
import Layout from "../Shared/Layout";
const RightConfigDetail = () => {
  const location = useLocation();
  const urlParams = new URLSearchParams(location.search);
  const rightConfigId = urlParams.get("id");
  const submitBtn = useRef(null);
  const [updatingRightConfig, setUpdatingRightConfig] = useState({});
  const [isUpdating, setIsUpdating] = useState(false);
  const [data, setData] = useState({
    name: "",
    explain: "",
    jobIds: [],
    rightIds: [],
  });
  const [jobTrees, setJobTrees] = useState([]);
  const [jobTreeExpandedKeys, setJobTreeExpandedKeys] = useState([]);
  const [rightTrees, setRightTrees] = useState([]);
  const [rightTreeExpandedKeys, setRightTreeExpandedKeys] = useState([]);
  // 递归遍历树 callback:(item:当前元素)=>void
  const recursion = useCallback((childrenPropertyName, array, callback) => {
    if (array) {
      array.forEach((item) => {
        recursion(childrenPropertyName, item[childrenPropertyName], callback);
        callback(item);
      });
    }
  }, []);
  const bind = useCallback(async () => {
    // 获取职位树
    const jobRes = await request("/job/tree", {}, "GET");
    if (jobRes.code >= 0) {
      const data = jobRes.data;
      const expandedKeys = [];
      recursion("childrenDeps", data, (item) => {
        item.disabled = true;
        expandedKeys.push(item.id);
        item.childrenDeps = [
          ...item.childrenDeps,
          ...item.childrenJobs.map((job) => ({ ...job, selectable: false })),
        ];
      });
      setJobTreeExpandedKeys(expandedKeys);
      setJobTrees(data);
    }
    // 获取权限树
    const rightRes = await request("/right/tree", {}, "GET");
    if (rightRes.code >= 0) {
      const data = rightRes.data;
      const expandedKeys = [];
      recursion("children", data, (item) => {
        expandedKeys.push(item.id);
        item.selectable = false;
      });
      setRightTreeExpandedKeys(expandedKeys);
      setRightTrees(data);
    }
    // 获取权限配置详情
    const rightConfigRes = await request(
      "/rightconfig/detail",
      { id: rightConfigId },
      "GET"
    );
    if (rightConfigRes.code >= 0) {
      setData(rightConfigRes.data);
    }
  }, [recursion, rightConfigId]);
  useEffect(() => {
    async function fecthData() {
      await bind();
    }
    fecthData();
  }, [bind]);
  const checkJobsAll = (e) => {
    const checked = e.target.checked;
    const checkedKeys = [];
    if (checked) {
      recursion("childrenDeps", jobTrees, (item) => {
        if (item.childrenDeps === undefined) {
          checkedKeys.push(item.id);
        }
      });
    }
    setUpdatingRightConfig({ ...updatingRightConfig, jobIds: checkedKeys });
  };
  const checkRightsAll = (e) => {
    const checked = e.target.checked;
    const checkedKeys = [];
    if (checked) {
      recursion("children", rightTrees, (item) => {
        checkedKeys.push(item.id);
      });
    }
    setUpdatingRightConfig({ ...updatingRightConfig, rightIds: checkedKeys });
  };
  const update = async () => {
    const res = await request(
      "/rightconfig/update",
      {
        id: updatingRightConfig.id,
        name: updatingRightConfig.name,
        explain: updatingRightConfig.explain,
        jobIds: updatingRightConfig.jobIds,
        rightIds: updatingRightConfig.rightIds,
      },
      "POST"
    );
    if (res.code >= 0) {
      setIsUpdating(false);
      message.success(res.message);
      await bind();
    } else {
      message.error(res.message || "更新失败");
    }
  };
  const toUpdate = () => {
    setIsUpdating(true);
    setUpdatingRightConfig({
      ...data,
    });
    console.log(updatingRightConfig);
  };
  const isSameArray = (arr1, arr2) => {
    if (arr1.length !== arr2.length) {
      return false;
    }
    let result = true;
    arr1.forEach((d) => {
      if (!arr2.includes(d)) {
        result = false;
      }
    });
    return result;
  };
  const dataIsChanged = () => {
    return (
      updatingRightConfig.name !== data.name ||
      updatingRightConfig.explain !== data.explain ||
      !isSameArray(updatingRightConfig.jobIds, data.jobIds) ||
      !isSameArray(updatingRightConfig.rightIds, data.rightIds)
    );
  };
  return (
    <Layout>
      <div style={{ height: "100%", overflow: "auto" }}>
        <div style={{ display: "flex" }}>
          <div style={{ fontWeight: "700" }}>权限配置详情</div>
          {!isUpdating ? (
            <div
              style={{ marginLeft: "auto", marginRight: "10px" }}
              onClick={toUpdate}
            >
              <MyButton type="warning">编辑</MyButton>
            </div>
          ) : (
            <div
              className="extra"
              style={{
                marginLeft: "auto",
                marginRight: "10px",
              }}
            >
              <div className="extra-btn" onClick={() => setIsUpdating(false)}>
                <MyButton>取消</MyButton>
              </div>
              <div className="extra-btn">
                <Button
                  type="primary"
                  onClick={() => {
                    submitBtn.current.click();
                  }}
                  disabled={!dataIsChanged()}
                >
                  保存
                </Button>
              </div>
            </div>
          )}
        </div>
        <div>
          {!isUpdating ? (
            <Descriptions
              layout="vertical"
              bordered
              column={1}
              items={[
                {
                  label: (
                    <span style={{ fontWeight: "700", fontSize: 16 }}>
                      名称
                    </span>
                  ),
                  key: "name",
                  children: data.name,
                },
                {
                  label: (
                    <span style={{ fontWeight: "700", fontSize: 16 }}>
                      描述
                    </span>
                  ),
                  key: "explain",
                  children: data.explain,
                },
              ]}
            />
          ) : (
            <Form
              onFinish={update}
              scrollToFirstError
              style={{
                paddingBlock: 32,
              }}
              labelCol={{
                span: 2,
              }}
              wrapperCol={{
                span: 22,
              }}
            >
              <Form.Item
                label="名称"
                name="name"
                initialValue={updatingRightConfig.name}
                rules={[{ required: true, message: "请输入名称" }]}
              >
                <Input
                  onChange={(event) =>
                    setUpdatingRightConfig({
                      ...updatingRightConfig,
                      name: event.target.value,
                    })
                  }
                  maxLength={100}
                  placeholder="请输入"
                />
              </Form.Item>
              <Form.Item
                label="描述"
                name="explain"
                initialValue={updatingRightConfig.explain}
                rules={[{ required: true, message: "请输入描述" }]}
              >
                <Input.TextArea
                  maxLength={1000}
                  rows={4}
                  onChange={(event) =>
                    setUpdatingRightConfig({
                      ...updatingRightConfig,
                      explain: event.target.value,
                    })
                  }
                  placeholder="请输入"
                />
              </Form.Item>
              <button
                style={{ display: "none" }}
                type="submit"
                ref={submitBtn}
              ></button>
            </Form>
          )}
        </div>
        <div style={{ display: "flex" }}>
          <div
            style={{
              flex: 1,
            }}
          >
            <h3 style={{ display: "flex" }}>
              选择职位
              <Checkbox
                style={{ marginLeft: "auto", marginRight: "10px" }}
                onChange={checkJobsAll}
                disabled={!isUpdating}
              >
                全选
              </Checkbox>
            </h3>
            <div>
              {!isUpdating ? (
                <Tree
                  checkable
                  blockNode
                  treeData={jobTrees}
                  expandedKeys={jobTreeExpandedKeys}
                  onExpand={(keys) => setJobTreeExpandedKeys(keys)}
                  checkedKeys={data.jobIds}
                  onCheck={(keys) => setData({ ...data, jobIds: keys })}
                  fieldNames={{
                    title: "name",
                    key: "id",
                    children: "childrenDeps",
                  }}
                  disabled={true}
                />
              ) : (
                <Tree
                  checkable
                  blockNode
                  treeData={jobTrees}
                  expandedKeys={jobTreeExpandedKeys}
                  onExpand={(keys) => setJobTreeExpandedKeys(keys)}
                  checkedKeys={updatingRightConfig.jobIds}
                  onCheck={(keys) =>
                    setUpdatingRightConfig({
                      ...updatingRightConfig,
                      jobIds: keys,
                    })
                  }
                  fieldNames={{
                    title: "name",
                    key: "id",
                    children: "childrenDeps",
                  }}
                />
              )}
            </div>
          </div>
          <div style={{ flex: 1 }}>
            <h3 style={{ display: "flex" }}>
              选择权限
              <Checkbox
                style={{ marginLeft: "auto", marginRight: "10px" }}
                onChange={checkRightsAll}
                disabled={!isUpdating}
              >
                全选
              </Checkbox>
            </h3>
            <div>
              {!isUpdating ? (
                <Tree
                  checkable
                  blockNode
                  treeData={rightTrees}
                  expandedKeys={rightTreeExpandedKeys}
                  onExpand={(keys) => setRightTreeExpandedKeys(keys)}
                  checkedKeys={data.rightIds}
                  onCheck={(keys) => setData({ ...data, rightIds: keys })}
                  fieldNames={{ title: "name", key: "id" }}
                  disabled={true}
                />
              ) : (
                <Tree
                  checkable
                  blockNode
                  treeData={rightTrees}
                  expandedKeys={rightTreeExpandedKeys}
                  onExpand={(keys) => setRightTreeExpandedKeys(keys)}
                  checkedKeys={updatingRightConfig.rightIds}
                  onCheck={(keys) =>
                    setUpdatingRightConfig({
                      ...updatingRightConfig,
                      rightIds: keys,
                    })
                  }
                  fieldNames={{ title: "name", key: "id" }}
                />
              )}
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
};
export default RightConfigDetail;
